/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "appmanager.h"
#include <QDBusError>
#include <QApplication>

AppManager::AppManager(QObject *parent)
    : QObject(parent)
    , m_appManagerInterface(new ComKylinAppManagerInterface("com.kylin.AppManager", "/com/kylin/AppManager", QDBusConnection::sessionBus()))
{
    if (!m_appManagerInterface->isValid()) {
        qWarning() << "Connect to com.kylin.AppManager dbus service failed!" << m_appManagerInterface->lastError();
    }
}

void AppManager::runApplication(const QString &desktopFile)
{
    auto reply = m_appManagerInterface->LaunchApp(desktopFile);
    while (!reply.isFinished()) {
        qApp->processEvents();
    }
    if (reply.isError()) {
        qWarning() << "Run Application failed!" << desktopFile << reply.error();
    } else {
        if (!reply.value()) {
            qWarning() << "Run Application failed!" << desktopFile;
        }
    }
}

QList<quint32> AppManager::runningApplications()
{
    QList<quint32> runningAppWids;
    return runningAppWids;
}

void AppManager::runApplicationConfig(const QString &desktopFile, const QStringList &Config)
{
    bool retConfig = m_appManagerInterface->LaunchAppWithArguments(desktopFile, Config);
    qDebug()<<"===retConfig"<<retConfig;
    if (!retConfig) {
        qWarning() << "Run ApplicationConfig failed!" << desktopFile;
    }
}

QString AppManager::AppDesktopFileNameByWid(qlonglong wid)
{
    return m_appManagerInterface->AppDesktopFileNameByWid(wid);
}

QStringList AppManager::getAppWhiteList()
{
    return m_appManagerInterface->AppWhiteList("AppUninstall");
}
